import 'package:flutter/foundation.dart';
import 'package:lib_module_manager/module_manager/handler.dart';
import 'package:lib_module_manager/module_manager/module_manager.dart';
import 'package:lib_module_manager/module_manager/page.dart';

typedef CreateModule = Module? Function({String? id});

abstract class Module {
  String type;
  String? id;

  late final Map<String, CreatePage> _createPageFuncs;

  late final List<Page> _pages = [];

  late final Map<String, CreateHandler>? _createHandlerFuncs;

  Module(
      {required this.type,
      this.id,
      required Map<String, CreatePage> createPageFuncs,
      Map<String, CreateHandler>? createHandlerFuncs})
      : _createPageFuncs = createPageFuncs,
        _createHandlerFuncs = createHandlerFuncs;

  Page? getPage({
    required String type,
    String? id,
    Map<String, dynamic>? params,
  }) {
    final int index = _pages
        .indexWhere((element) => element.type == type && element.id == id);
    if (index != -1) {
      return _pages[index];
    }

    CreatePage? createPage = _createPageFuncs[type];
    if (createPage == null) {
      return null;
    }

    final Page? page = createPage(module: this, id: id, params: params);
    if (page != null) {
      _pages.add(page);
    }
    return page;
  }

  void removePage({required String type, String? id}) {
    _pages.removeWhere((element) => element.type == type && element.id == id);

    if (kDebugMode) {
      print("Remove page type: $type, id: ${id ?? ""}");
      print("Page count: ${_pages.length}");
    }

    if (_pages.isEmpty) {
      ModuleManager.instance.removeModule(type: this.type, id: this.id);
    }
  }

  Handler? getHandler({required String type}) {
    CreateHandler? createHandler = _createHandlerFuncs?[type];
    if (createHandler == null) {
      return null;
    }

    return createHandler();
  }
}
